package cas;

import java.util.concurrent.atomic.AtomicStampedReference;

public class ABADemo2_work {
        private static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);

        public static void main(String[] args) {
            new Thread(() -> {
                int stamp = atomicStampedReference.getStamp();
                System.out.println(Thread.currentThread().getName() + " 的版本号为：" + stamp);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                atomicStampedReference.compareAndSet(100, 101, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1 );
                System.out.println(Thread.currentThread().getName() + " 的版本号为：" +  atomicStampedReference.getStamp());
                atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1 );
                System.out.println(Thread.currentThread().getName() + " 的版本号为：" +  atomicStampedReference.getStamp());

            }).start();

            new Thread(() -> {
                int stamp = atomicStampedReference.getStamp();
                System.out.println(Thread.currentThread().getName() + " 的版本号为：" + stamp);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                boolean b = atomicStampedReference.compareAndSet(100, 2019, stamp, stamp + 1);
                System.out.println(b); // false
                System.out.println(atomicStampedReference.getReference()); // 100
            }).start();
    }
}
